﻿using System;
using System.Net.Sockets;
using System.IO;
using System.ComponentModel;


namespace ThePushCSharp
{
    public class Client
    {
        public bool active;
        public TcpClient myclient;
        public NetworkStream networkStream;
        public StreamReader streamReader;
        public StreamWriter streamWriter;
        public ThePush game;

        public Client(ThePush game)
        {
            active = false;
            this.game = game;
        }

        //Attempts to connect to a server
        public void connect(String serverIp, int port)
        {
            try
            {
                myclient = new TcpClient(serverIp, port);
                active = true;
            }
            catch
            {
                return;
            }

            networkStream = myclient.GetStream();
            streamReader = new StreamReader(networkStream);
            streamWriter = new StreamWriter(networkStream);
        }

        //Frees up the read/write streams ONLY if this was active
        public void close()
        {
            if (!active)
                return;

            streamReader.Close();
            streamWriter.Close();
            networkStream.Close();
        }

        //Attempts to receive data on the socket stream
        public int recv()
        {
            String msg = streamReader.ReadLine();

            if (msg.Length < 2) //too short
                return 0;

            char msgType = msg[0];
            int size = (int)msg[1];
            msg.Remove(0, 2);

            return 1;
        }

        //Attemps to send data to the socket stream
        public int send(char messageType, String parameters)
        {
            try
            {
                streamWriter.WriteLine(messageType + parameters.Length + parameters);
                streamWriter.Flush();
            }
            catch
            {
                return -1;
            }

            return 1;
        }

    }
}